<?php


namespace app\service;


use app\entity\ActMsgEntity;
use app\exception\ErrorCode;
use app\exception\OaException;
use app\models\request\ReqActListPage;
use app\models\request\ReqId;
use app\models\response\RespPage;
use yii\data\Pagination;

class MsgService
{

    public function count($userId){
        return  ActMsgEntity::find()->where(["user_id"=>$userId,"is_read"=>0])->count();
    }


    /**
     * @param $id
     * @return array|\yii\db\ActiveRecord|ActMsgEntity
     * @throws OaException
     */
    public function findById($id){
        $entity = ActMsgEntity::find()->where(["id"=>$id])->one();
        if(!$entity) {
            throw new OaException(ErrorCode::NOT_404);
        }
        return $entity;
    }

    public function read(ReqId $req) {
        $id = $req->getId();

        $entity = $this->findById($id);
        if ($entity->getUserId()!=$req->getUserId()) {
            throw new OaException(ErrorCode::NOT_404);
        }
        $entity->setIsRead(1);
        $entity->setUpdateTime(date("Y-m-d G:i:s"));
        $entity->save();
        return true;
    }


    /**
     * @param int $userId
     * @return RespPage
     */
    public function listPage(ReqActListPage $req) {
        $data = ActMsgEntity::find()->where(["del_flag"=>0])->orderBy("id desc");

        if ($req->getUserId()) {
            $data->andWhere(["user_id"=>$req->getUserId()]);
        }


        $pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => $req->getPageSize(),'page'=>$req->getPageNo()-1]);
        /**@var $entities ActMsgEntity[]*/
        $entities = $data->offset($pages->getOffset())->limit($pages->getLimit())->all();
        $list = [];
        foreach ($entities as $entity) {

            array_push($list,[
                "id"=>$entity->getId(),
                "type"=>$entity->getType(),
                "title"=>$entity->getTitle(),
                "content"=>$entity->getContent(),
                "create_time"=>$entity->getCreateTime(),
                "is_read"=>$entity->getIsRead(),
            ]);
        }

        $resp = new RespPage();
        $resp->setTotal(intval($pages->totalCount));
        $resp->setPageSize($pages->getPageSize());
        $resp->setPageNo($req->getPageNo());
        $resp->setList($list);
        return $resp;
    }
}